package com.boruan.shengtangfeng.admin.controller;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.boruan.shengtangfeng.admin.jwt.UserSubject;
import com.boruan.shengtangfeng.admin.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.dao.IModuleQuestionDao;
import com.boruan.shengtangfeng.core.dto.QuestionDto;
import com.boruan.shengtangfeng.core.dto.mapper.QuestionDtoMapper;
import com.boruan.shengtangfeng.core.entity.Log;
import com.boruan.shengtangfeng.core.entity.Log.OperateType;
import com.boruan.shengtangfeng.core.enums.QuestionType;
import com.boruan.shengtangfeng.core.entity.Question;
import com.boruan.shengtangfeng.core.entity.QuestionComment;
import com.boruan.shengtangfeng.core.service.ILogService;
import com.boruan.shengtangfeng.core.service.IQuestionService;
import com.boruan.shengtangfeng.core.service.impl.ConfigService;
import com.boruan.shengtangfeng.core.service.impl.QuestionCommentService;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.vo.QuestionCommentVo;
import com.boruan.shengtangfeng.core.vo.QuestionVo;
import com.boruan.shengtangfeng.core.vo.mapper.QuestionCommentVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.QuestionVoMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/admin/question")
@Api(value = "", tags = {"NO:14 试题接口"})
public class QuestionApi {
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private ILogService sysLogService;
    @Autowired
    private QuestionCommentService questionCommentService;
    @Autowired
    private IModuleQuestionDao iModuleQuestionDao;
    @Autowired
    private ConfigService configService;

    @CrossOrigin
    @GetMapping(value = "/getQuestionType")
    @ApiOperation(value = "NO:14-1 查看试题类型", notes = "")
    public GlobalReponse<QuestionType[]> getQuestionType() {
        return GlobalReponse.success(QuestionType.values());
    }

    @CrossOrigin
    @PostMapping(value = "/getQuestions")
    @ApiOperation(value = "NO:14-4 查看试题列表", notes = "")
    public GlobalReponse<QuestionVo> getQuestion(@RequestBody QuestionDto questionDto,
                                                 @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                 @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        PageQuery<Question> pageData = new PageQuery<Question>();
        pageData.setPageNumber(pageNo);
        if(pageSize==0){
            pageSize=30000;
        }

        pageData.setPageSize(pageSize);
        questionService.pageQuery(pageData, QuestionDtoMapper.MAPPER.toEntity(questionDto));
        List<QuestionVo> resultList = QuestionVoMapper.MAPPER.toVo(pageData.getList());
        pageData.setList(resultList);
        return GlobalReponse.success().setData(pageData);
    }
    


    @CrossOrigin
    @PostMapping(value = "/saveQuestion")
    @ApiOperation(value = "NO:14-5 新增试题", notes = "")
    public GlobalReponse saveQuestion(@RequestBody QuestionDto questionDto) {
        try {
            UserSubject userSubject = JwtUtil.getCurrentJwtUser();
            Log sysLog = new Log();
            if (questionDto.getId() == null) {
                // 添加
                Question question = QuestionDtoMapper.MAPPER.toEntity(questionDto);
                question.setCreateBy(userSubject.getName());
//                question.setAccurate(new BigDecimal(1));
                question.setCreateTime(new Date());
                question.setStatus(1);
                question.setUpdateTime(new Date());
                question.setIsDeleted(false);
                question.setAccurate(new BigDecimal(0));
                question.setWarehouseType(0);
                questionService.save(question);
                questionService.insertQuestionGrade(question.getId(), questionDto.getGradeIds());

                sysLog.setObjectId(question.getId());
                sysLog.setContent("管理员添加试题信息");
                sysLog.setOperateType(OperateType.ADD);
            } else {
                // 更新
                Question old = questionService.findById(questionDto.getId());
                old.setUpdateBy(userSubject.getName());
                old.setAnswer(questionDto.getAnswer());
                old.setStatus(1);
                old.setScore(questionDto.getScore());
                old.setContent(questionDto.getContent());
                old.setType(questionDto.getType());
                old.setTitle(questionDto.getTitle());
                old.setTextExplain(questionDto.getTextExplain());
                old.setUpdateTime(new Date());
                old.setIsDeleted(false);
                old.setSubjectId(questionDto.getSubjectId());
                old.setWarehouseType(0);
                questionService.save(old);
                questionService.insertQuestionGrade(questionDto.getId(), questionDto.getGradeIds());
                sysLog.setObjectId(old.getId());
                sysLog.setContent("管理员修改试题信息");
                sysLog.setOperateType(OperateType.UPDATE);
            }
            sysLog.setCreateTime(new Date());
            sysLog.setOperater(userSubject.getId());
            sysLog.setLogType(Log.LogType.ADMIN);
            sysLogService.save(sysLog);
            return GlobalReponse.success();
        } catch (Exception e) {
            log.error("管理员编辑试题失败:{}", e);
            return GlobalReponse.fail();
        }

    }

    @CrossOrigin
    @PostMapping(value = "/deleteAllQuestion")
    @ApiOperation(value = "NO:14-6 删除试题", notes = "")
    public GlobalReponse<QuestionVo> deleteAllQuestion(List ids) {
        try {
            ids.forEach(id -> {
                Long i = (Long) id;
                UserSubject userSubject = JwtUtil.getCurrentJwtUser();
                Question question = questionService.findById(i);
                question.setIsDeleted(true);
                question.setUpdateBy(userSubject.getId().toString());
                question.setUpdateTime(new Date());

            });
            return GlobalReponse.success();
        } catch (Exception e) {
            log.error("管理员删除试题失败:{}", e);
            return GlobalReponse.fail();
        }
    }

    /**
     * @param ids
     * @return
     * @author:twy
     * @Descrition:删除题目
     */
    @PostMapping(value = "/deleteByIds")
    @ApiOperation(value = "NO:14-8根据id删除题目", notes = "")
    public GlobalReponse delById(String ids) {
        UserSubject user = JwtUtil.getCurrentJwtUser();
        if (questionService.delById(ids, user.getId()) > 0) {
            return GlobalReponse.success();
        } else {
            return GlobalReponse.fail();
        }
    }

    @CrossOrigin
    @GetMapping(value = "/getQuestionById")
    @ApiOperation(value = "NO:14-7 根据id查询试题", notes = "")
    public GlobalReponse<QuestionVo> getQuestionById(@RequestParam(required = false) Long id) {
        Question question = questionService.findById(id);
        QuestionVo questionVo = QuestionVoMapper.MAPPER.toVo(question);
        List<Long> grades=questionService.getQuestionGrades(id);
        questionVo.setGradeIds(grades);
        return GlobalReponse.success().setData(questionVo);
    }


    @GetMapping("/getModuleQuestion")
    @ApiOperation(value = "NO:14-9 获取模块下的题目", notes = "")
    public GlobalReponse<List<QuestionVo>> getModuleQuestion(@RequestParam(value = "moduleId") Long moduleId) {
        List<Question> result = questionService.findByModule(moduleId);
        return GlobalReponse.success(QuestionVoMapper.MAPPER.toVo(result));
    }



    @GetMapping("/getQuestionComment")
    @ApiOperation(value = "NO:14-17 获取题目下的评论", notes = "")
    public GlobalReponse<List<QuestionCommentVo>> getQuestionComment(Long questionId) {
        List<QuestionComment> videos = questionCommentService.findByQuestionId(questionId, 1, 0);
        return GlobalReponse.success(QuestionCommentVoMapper.MAPPER.toVo(videos));
    }


}
